package NetModel.okhttp.requset;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;


import java.io.FileNotFoundException;
import java.util.concurrent.TimeUnit;

import NetModel.okhttp.OkHttpClientManger;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2016/10/27.
 */
public class PutByteRequestBuilder extends BaseRequest<PutByteRequestBuilder> {

    private static final String TAG = "PutByteRequestBuilder";
    private byte[] bytes;
    private Integer offset;
    private Integer byteCount;

    @Override
    public Call build() {
        Request req = new Request.Builder()
                .url(url)
                .headers(addHead(heads))
                .put(addByteBody(bytes))
                .tag(tag)
                .build();
        Call call = OkHttpClientManger.getInstance().getClient().newBuilder()
                .writeTimeout(50, TimeUnit.SECONDS)
                .readTimeout(50, TimeUnit.SECONDS).build().newCall(req);
        return call;
    }


    private RequestBody addByteBody(@NonNull byte[] bytes) {
        if (offset != null && byteCount != null) {
            return RequestBody.create(MediaType.parse("application/octet-stream"), bytes, offset, byteCount);
        } else {
            return RequestBody.create(MediaType.parse("application/octet-stream"), bytes);
        }
    }


    public <T extends BaseRequest> T content(byte[] bytes, @Nullable Integer offset, @Nullable Integer byteCount) throws FileNotFoundException {
        this.bytes = bytes;
        this.offset = offset;
        this.byteCount = byteCount;
        return (T) this;
    }
}
